﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace NetMongo.Data
{
    public class ManagerConfig
    {
        public static string ConfigPath;
        //加载配置文件
        static ManagerConfig()
        {
            ConfigPath = "D:/Project/NetMongo/NetMongo/config.xml";
        }
        //xml序列化后的对象
        private static ServiceConfig _settings;
        public static ServiceConfig ServiceSettings
        {
            get
            {
                return _settings ?? (_settings = Load());
            }
        }

        private static object lockObj = new object();

        //加载xml序列化为ServiceConfig对象
        static ServiceConfig Load()
        {
            if (File.Exists(ConfigPath))
            {
                lock (lockObj)
                {
                    using (FileStream fs = new FileStream(ConfigPath, FileMode.Open))
                    {
                        try
                        {
                            XmlSerializer xs = new XmlSerializer(typeof(ServiceConfig));
                            //序列化为一个对象
                            _settings = (ServiceConfig)xs.Deserialize(fs);
                        }
                        catch (Exception ex)
                        {
                            fs.Close();
                            fs.Dispose();
                        }
                    }
                }
            }
            else
            {
                throw new Exception("数据库配置文件不存在，请检查");
                //_settings = new ServiceConfig();
            }

            return _settings;
        }
    }
}
